"""LLM Plays Pokemon 知识库工具模块"""

import logging
from typing import Dict, Any, Optional

from llm_pokemon.knowledge.base import KnowledgeBase

logger = logging.getLogger(__name__)


class KnowledgeBaseTool:
    """知识库工具类，提供update_knowledge_base功能"""
    
    def __init__(self, knowledge_base: KnowledgeBase):
        """初始化知识库工具
        
        Args:
            knowledge_base: 知识库实例
        """
        self.knowledge_base = knowledge_base
        logger.info("知识库工具初始化完成")
    
    def execute(self, operation: str, section_id: str, content: Optional[str] = None) -> Dict[str, Any]:
        """执行知识库操作
        
        Args:
            operation: 操作类型，可选值：'add', 'update', 'delete', 'get'
            section_id: 部分ID
            content: 部分内容，仅在add和update操作时需要
            
        Returns:
            操作结果
        """
        logger.info(f"执行知识库操作: {operation} - {section_id}")
        
        result = {
            "success": False,
            "message": "",
            "data": None
        }
        
        try:
            if operation == "add" or operation == "update":
                if content is None:
                    result["message"] = f"执行 {operation} 操作需要提供内容"
                    return result
                
                self.knowledge_base.set_section(section_id, content)
                result["success"] = True
                result["message"] = f"已{operation}知识库部分: {section_id}"
                
            elif operation == "delete":
                success = self.knowledge_base.delete_section(section_id)
                result["success"] = success
                if success:
                    result["message"] = f"已删除知识库部分: {section_id}"
                else:
                    result["message"] = f"知识库部分不存在: {section_id}"
                    
            elif operation == "get":
                content = self.knowledge_base.get_section(section_id)
                result["success"] = True
                result["data"] = content
                if content is None:
                    result["message"] = f"知识库部分不存在: {section_id}"
                else:
                    result["message"] = f"已获取知识库部分: {section_id}"
                    
            else:
                result["message"] = f"未知操作: {operation}"
                
            # 保存知识库
            if result["success"] and operation != "get":
                self.knowledge_base.save()
                
        except Exception as e:
            logger.error(f"执行知识库操作失败: {e}")
            result["message"] = f"执行知识库操作失败: {str(e)}"
            
        return result